package org.apache.http.examples.client;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpHost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;

public class HttpUtil {
    
    public static CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
//        HttpClientBuilder clientBuilder = HttpClients.custom();
            HttpHost proxy = new HttpHost("127.0.0.1", 8888);
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            HttpClientBuilder clientBuilder = HttpClients.custom().setRoutePlanner(routePlanner);
      //创建TrustManager
        X509TrustManager xtm = new X509TrustManager(){ 
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
            public X509Certificate[] getAcceptedIssuers() { return null; } 
        }; 
        //TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext 
        //注意：经测试发现，这里必须是"SSL"实例而非“TLS”，具体原因还不清楚
        SSLContext ctx = SSLContext.getInstance("SSL");  
        //使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用 
        ctx.init(null, new TrustManager[]{xtm}, null); 

        //创建SSLSocketFactory 
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx);
        clientBuilder.setSSLSocketFactory(socketFactory);
        return clientBuilder.build();
    }
    
}
